import type { APIRoute } from 'astro';
import { getCollection, type CollectionEntry } from 'astro:content';
import { generateOgImageForPost } from '@/utils/ogImage/generate';
import config from '@/config';

export async function getStaticPaths() {
  if (!config.dynamicOgImage) {
    return [];
  }

  const posts = await getCollection('blog').then(p =>
    p.filter(({ data }) => !data.draft && !data.ogImage)
  );

  return posts.map(post => ({
    params: { slug: post.slug },
    props: post,
  }));
}

export const GET: APIRoute = async ({ props }) => {
  if (!config.dynamicOgImage) {
    return new Response(null, {
      status: 404,
      statusText: 'Not found',
    });
  }

  return new Response(
    (await generateOgImageForPost(props as CollectionEntry<'blog'>)) as BodyInit,
    {
      headers: { 'Content-Type': 'image/png' },
    }
  );
};
